<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomTag\Action\Dashboard;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\RoomTag\Contract\RoomTagPivotContract;

/**
 * 创建客户群标签.
 *
 * Class RoomTagStore
 * @Controller
 */
class RoomTagStore extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var RoomTagPivotContract
     */
    protected $roomTagPivotService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/roomTag/roomTagStore", methods="POST")
     */
    public function handle()
    {
        $user = user();
        # # 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 接收参数
        $params['roomIds'] = $this->request->input('roomIds');
        $params['tagIds'] = $this->request->input('tagIds');

        // 验证参数
        $this->validated($params);

        # # 数据操作
        Db::beginTransaction();
        try {
            # # 添加群标签
            foreach ($params['roomIds'] as $roomId) {
                foreach ($params['tagIds'] as $tagId) {
                    if (! empty($this->roomTagPivotService->getRoomTagPivotsByRoomIdTagId($roomId, $tagId))) {
                        continue;
                    }
                    $data = [
                        'room_id' => $roomId,
                        'employee_id' => user()['workEmployeeId'],
                        'room_tag_id' => $tagId,
                        'type' => 1,
                        'created_at' => date('Y-m-d H:i:s'),
                    ];
                    $this->roomTagPivotService->createRoomTagPivot($data);
                }
            }
            Db::commit();
            return [];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '添加群标签失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'roomIds' => 'required|array',
            'tagIds' => 'required|array',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'roomIds.required' => '客户群id 必传',
            'tagIds.required' => '标签id 必传',
        ];
    }
}
